package cn.gdut.chengcai.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gdut.chengcai.base.CommentUtil;
import cn.gdut.chengcai.base.ConstantUtil;
import cn.gdut.chengcai.base.CourseUtil;
import cn.gdut.chengcai.base.JsonUtil;
import cn.gdut.chengcai.base.MessageUtil;
import cn.gdut.chengcai.base.Pager;
import cn.gdut.chengcai.base.PagerUtil;
import cn.gdut.chengcai.base.ResponseData;
import cn.gdut.chengcai.base.UploadDownloadUtil;
import cn.gdut.chengcai.entity.CommentInfo;
import cn.gdut.chengcai.entity.CommentInfoExample;
import cn.gdut.chengcai.entity.CourseChapterInfo;
import cn.gdut.chengcai.entity.CourseChapterInfoExample;
import cn.gdut.chengcai.entity.CourseInfo;
import cn.gdut.chengcai.entity.CourseLessonInfo;
import cn.gdut.chengcai.entity.CourseLessonInfoExample;
import cn.gdut.chengcai.param.CourseSearchParam;
import cn.gdut.chengcai.service.CommentInfoService;
import cn.gdut.chengcai.service.CourseChapterInfoService;
import cn.gdut.chengcai.service.CourseInfoService;
import cn.gdut.chengcai.service.CourseLessonInfoService;
import cn.gdut.chengcai.vo.CommentInfoVo;
import cn.gdut.chengcai.vo.CourseChapterInfoVo;
import cn.gdut.chengcai.vo.CourseInfoVo;
import cn.gdut.chengcai.vo.CourseLessonInfoVo;

@Controller
@RequestMapping("/course")
public class CourseController {

	@Autowired
	protected CourseInfoService courseInfoService;

	@Autowired
	protected CourseChapterInfoService courseChapterInfoService;

	@Autowired
	protected CourseLessonInfoService courseLessonInfoService;

	@Autowired
	protected CommentInfoService commentInfoService;

	/**
	 * 课程详情页
	 */
	@RequestMapping("/{courseId}/detail")
	public String detail(HttpSession session, ModelMap map, @PathVariable Long courseId) {

		CourseInfo entity = courseInfoService.selectByPrimaryKey(courseId);
		if (entity.getViewCount() != null) {
			entity.setViewCount(entity.getViewCount() + 1);
		} else {
			entity.setViewCount(1L);
		}
		courseInfoService.updateByPrimaryKey(entity);

		CourseInfoVo vo = new CourseInfoVo();
		try {
			CourseUtil.fillVo(entity, vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("entity", vo);

		// 课程章节列表
		CourseChapterInfoExample chapterInfoExample = new CourseChapterInfoExample();
		CourseChapterInfoExample.Criteria chapterCriteria = chapterInfoExample.createCriteria();
		chapterCriteria.andCourseIdEqualTo(entity.getId());
		chapterCriteria.andCourseSnEqualTo(entity.getSn());
		chapterCriteria.andIsDeletedEqualTo(false);
		List<CourseChapterInfo> chapterInfos = courseChapterInfoService.selectByExample(chapterInfoExample);
		List<CourseChapterInfoVo> chapterInfoVos = new ArrayList<>();

		try {
			CourseUtil.fillChapterVoList(chapterInfos, chapterInfoVos);
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("chapterList", chapterInfoVos);

		// 课程节列表
		CourseLessonInfoExample lessonInfoExample = new CourseLessonInfoExample();
		CourseLessonInfoExample.Criteria lessonCriteria = lessonInfoExample.createCriteria();
		lessonCriteria.andCourseIdEqualTo(entity.getId()).andCourseSnEqualTo(entity.getSn()).andIsDeletedEqualTo(false);
		List<CourseLessonInfo> lessonInfos = courseLessonInfoService.selectByExample(lessonInfoExample);
		List<CourseLessonInfoVo> lessonInfoVos = new ArrayList<>();
		try {
			CourseUtil.fillLessonVoList(lessonInfos, lessonInfoVos);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		map.put("lessonList", lessonInfoVos);

		// 课程评论列表
		CommentInfoExample example = new CommentInfoExample();
		example.createCriteria().andIsDeletedEqualTo(false).andTargetIdEqualTo(courseId);
		example.setOrderByClause("create_time_ desc");
		List<CommentInfo> listTotal = commentInfoService.selectByExample(example);
		Long itemCount = Long.valueOf(String.valueOf(listTotal.size()));
		Pager pager = PagerUtil.getPager(session, itemCount);
		int fromIndex = (pager.getPageNo() - 1) * pager.getPageSize();
		if (fromIndex >= listTotal.size()) {
			fromIndex = 0;
			pager.setPageNo(1);
			session.setAttribute(ConstantUtil.STR_PAGE_NO, "1");
		}
		int toIndex = fromIndex + pager.getPageSize();
		if (toIndex >= listTotal.size()) {
			toIndex = listTotal.size();
		}

		List<CommentInfo> list = listTotal.subList(fromIndex, toIndex);
		List<CommentInfoVo> voList = new ArrayList<>();
		if (list != null && list.size() > 0) {
			try {
				CommentUtil.fillVoList(list, voList);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		map.put("commentList", voList);
		session.setAttribute("pager", pager);

		return "/course/detail";
	}

	/**
	 * 课程播放页
	 */
	@RequestMapping("/member/{id}/display")
	public String display(HttpSession session, ModelMap map, @PathVariable Long id) {

		try {
			// 获取课程视频路径
			CourseLessonInfo entity = courseLessonInfoService.selectByPrimaryKey(id);
			String filename = entity.getCoursewareUrl();
			String path = UploadDownloadUtil.getResourceUrl(filename);
			String pattern = "d:/camp-uploads\\courseware";
			path = path.substring(pattern.length(), path.length());
			String head = "/resource";
			path = head + path.replace("\\", "/");
			session.setAttribute(ConstantUtil.COURSE_LESSON_URL, path);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "/course/display";
	}

	/**
	 * 课程搜索页
	 */
	@RequestMapping("/search")
	public String search(HttpSession session, ModelMap map) {

		try {
			if (session.getAttribute(ConstantUtil.SESSION_SEARCH_PARAM) instanceof CourseSearchParam) {

			} else {
				session.setAttribute(ConstantUtil.SESSION_SEARCH_PARAM, null);
			}
			CourseUtil.filter(session, map, courseInfoService, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "/course/search";
	}

	/**
	 * 课程搜索操作
	 */
	@RequestMapping(value = "/searchAction", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData<Object> searchAction(@RequestBody String jsonString, HttpServletRequest request,
			HttpSession session, ModelMap map) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {

			CourseSearchParam param = (CourseSearchParam) JsonUtil.fromJson(jsonString, CourseSearchParam.class);
			CourseUtil.resetSearchParam(param);
			session.setAttribute(ConstantUtil.SESSION_SEARCH_PARAM, param);
			/*
			 * List<CourseInfoVo> voList = CourseUtil.filter(session, map,
			 * courseInfoService, param); result.setData(voList);
			 */

			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			return result;
		}

		return result;
	}

	/**
	 * 获取课程搜索初始默认条件
	 */
	@RequestMapping(value = "/resetSearchFilterAction", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData<Object> resetSearchFilterAction(@RequestBody String jsonString, HttpServletRequest request,
			HttpSession session) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {

			CourseSearchParam param = (CourseSearchParam) session.getAttribute(ConstantUtil.SESSION_SEARCH_PARAM);
			if (param == null) {
				param = new CourseSearchParam();
				CourseUtil.resetSearchParam(param);
			}
			result.setData(param);
			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
		}

		return result;
	}

	/**
	 * 课程搜索过滤
	 */
	@RequestMapping(value = "/reloadDataAction", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData<Object> reloadDataAction(@RequestBody String jsonString, HttpSession session, ModelMap map) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);

		CourseSearchParam param = (CourseSearchParam) JsonUtil.fromJson(jsonString, CourseSearchParam.class);
		try {
			List<CourseInfoVo> voList = CourseUtil.filter(session, map, courseInfoService, param);
			result.setData(voList);
			result.setPager((Pager) session.getAttribute("pager"));
			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
		}
		return result;
	}

}
